# -*- coding:utf-8 -*-
'''
author:***y
time:2019-08-28
主要功能说明：
1、获取登录接口的token
2、介入闲聊和qa问答，批量测试闲聊和qa模型，得出模型的正确率；
这里使用的比较方法是比较闲聊和qa的得分，然后得分比较高的则保存到数据表中
'''
import requests
import csv
import pandas as pd
import json

class TestAi():

    def __init__(self):
        # 初始化登录接口
        # login_url = 'https://api.icarbonx.com/oauth2/token?grant_type=password&sms_verify=true'
        # login_header = {"Authorization": "Basic Y29tLm1ldW0uY29hY2guaXBob25lOjdmYTYyZmFmYzgxZTgwMzY="}
        # login_data = {
        #     "username": "15012345678",
        #     "password": "888888",
        #     "appName": "health-buddy",
        #     "grant_type": "password",
        #     "sms_verify": "true"
        # }
        # # 登录请求接口
        # r_login = requests.post(url=login_url, data=login_data, headers=login_header)
        print("ok")


    def login_token(self):

        # 初始化登录接口
        login_url = 'https://api.icarbonx.com/oauth2/token?grant_type=password&sms_verify=true'
        login_header = {"Authorization": "Basic Y29tLm1ldW0uY29hY2guaXBob25lOjdmYTYyZmFmYzgxZTgwMzY="}
        login_data = {
            "username": "15012345678",
            "password": "888888",
            "appName": "health-buddy",
            "grant_type": "password",
            "sms_verify": "true"
        }
        # 登录请求接口
        r_login = requests.post(url=login_url, data=login_data, headers=login_header)
        # # 获取登录的响应报文
        # print(r_login.text)
        # login_response = json.loads(r_login.text)
        # # 保存登录的token信息
        # access_token = login_response['access_token']
        token = r_login.json()['access_token']
        print(token)
        '''请求接口获取token值'''
        return token

    def qa_chat(self):

        # 初始化回复失败的变量
        qa_flag_init = 0
        qa_error_init = 0
        qa_error_fail_init = 0


        #读取csv文件
        with open('E:\\test\\HB\\pyqa.csv','r') as csvFile:
            reader = csv.reader(csvFile)
            print(type(reader))
            next(reader)
            for row in reader:
                print(row)
                print(type(row))
                print(row[1])
                print(type(row[1]))


                #食物qa问答接口的请求参数msg
                qa_msg = {"msg":row[1]}
                print(qa_msg)
                # 获取登录的token
                qa_headers = {"Authorization": "Bearer " + self.login_token()}
                # qa问答的url
                qa_url = 'https://api.icarbonx.com/chatbot/qa'
                # qa问答模型接口请求
                r_qa = requests.post(url = qa_url,data= qa_msg,headers = qa_headers)
                # 获取响应报文
                print(r_qa.text)
                # 转换响应结果为dict格式
                qa_response = json.loads(r_qa.text)
                print(qa_response)
                print(type(qa_response))

                # 判断响应结果是否为空,不为空，则获取answer和score的值
                if qa_response:
                    print(qa_response[0])
                    qa_response_all = qa_response[0]
                    #获取answer的值
                    qa_response_answer = qa_response_all['answer']
                    qa_response_score = qa_response_all['score']
                    print("qa的answer：" + qa_response_answer)
                else:
                    qa_flag_init = qa_flag_init + 1
                    print("qa问答失败%d" %qa_flag_init)


                # chat闲聊模型请求，闲聊的url
                chit_url = 'https://api.icarbonx.com/chit/st'
                #闲聊的接口请求
                r_chit = requests.post(url= chit_url,data = qa_msg,headers= qa_headers)
                #获取响应报文
                print(r_chit.text)
                #转换响应结果为dict
                chit_response = json.loads(r_chit.text)
                print(chit_response)
                print(type(chit_response))

                #判断响应结果是否为空，不为空，则获取answer和score的值
                if chit_response:
                    print(chit_response[0])
                    chit_response_all = chit_response[0]
                    #获取answer和score的值
                    chit_response_answer = chit_response_all['answer']
                    chit_response_score = chit_response_all['score']
                    print("chit的answer" + chit_response_answer)
                else:
                    qa_error_init = qa_error_init + 1
                    print("闲聊失败%d" % qa_error_init)
                    print("先睡了")
                # 如何qa的分值大于闲聊，则返回qa的answer
                data_row = ['question','answer']
                if qa_response_score > chit_response_score:

                    qa_msg_answer = qa_response_answer
                    # # 保存qa的answer到本地文件as
                    # with open('E:\\test\\HB\\answer.csv','a',encoding='utf-8-sig') as f:
                    #     csv_write = csv.writer(f)
                    #     data_row[1] = qa_msg_answer
                    #     data_row[0] = row[1]
                    #
                    #     print(type(data_row))
                    #     csv_write.writerow(data_row)
                    #     print("qa的回答")
                    #     f.close()
                else:
                    qa_msg_answer = chit_response_answer

                # 如果返回结果中存在\n换行符，则替换成为分号；
                if '\n' in qa_msg_answer:
                    qa_msg_answer = qa_msg_answer.replace("\n",";")

                # 去掉回答结果中的逗号
                qa_msg_answer = qa_msg_answer.replace(",","")


                # 保存chit的answer到本地文件
                with open('E:\\test\\HB\\answer.csv','a',encoding='utf-8-sig') as f:
                    # csv_write = csv.writer(f)
                    data_row[0] = row[1]
                    data_row[1] = qa_msg_answer



                        # data_row = list(data_row)
                        # print(data_row)
                    f.write(','.join(data_row))
                    f.write("\n")
                    # f.write("\\n")
                    print("chit的问答")
                    f.close()




        # 关闭csv
        csvFile.close()



if __name__ == '__main__':

    qc = TestAi()
    qc.qa_chat()
